package com.example.redis_rate_limiter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description : 拦截器实现
 * @Author : ZYX
 * @Date : 2022/6/7 16:10
 * @Version : 1.0
 **/
@Configuration
public class RequestInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisLimitExcutor redisLimitExcutor;

    /**
     * 只有返回true时才继续执行，返回false取消当前请求
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 根据实际情况设置QPS
         */
        String url = request.getRequestURI();
        String ip = IpUtil.getIpAddr(request);
        //QPS设置为5，手动刷新接口可以测试出来
        if (!redisLimitExcutor.tryAccess(ip+url, 5, 1)) {
            throw new RuntimeException("调用频繁");
        } else {
            return true;
        }
    }
}
